package com.lxj.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import com.lxj.charactor.Hero;

/**
 * TestJdbc4
 */
public class TestJdbc4 {
    public static void main(String[] args) {
        Hero h = get(20);
        System.out.println(h.name);
        add(new Hero("焦喜亮",3434,89));

    }

    public static void add(Hero hero) {
        try {
            String sql = "insert into hero (`name`,`hp`,`damage`) values ('"+hero.name+"',"+hero.hp+","+hero.damage+")";

            Statement s = getCon();

            // 执行sql语句
            s.execute(sql);
            // 
            // ResultSet rs = s.getGeneratedKeys();
            // int id;
            // if(rs.next()) {
            //     id = rs.getInt(1);
            // }

            System.out.printf("添加的数据：姓名--%s\t 血量--%f\t damage--%f%n", hero.name, hero.hp, hero.damage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // public static void update()

    /**
     * 获取
     * @param id
     * @return
     */
    public static Hero get(int id) {
        
        Hero hero = null;
        try {
            String sql = "select * from hero where id = " + id;
            // s.execute(sql);
            Statement s = getCon();
            ResultSet rs = s.executeQuery(sql);

            if(rs.next()) {
                String name = rs.getString("name");
                int hp = rs.getInt("hp");
                int damage = rs.getInt("damage");
                
                hero = new Hero();
                hero.name = name;
                hero.hp = hp;
                hero.damage = damage;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hero;
    }

    public static Statement getCon() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/how2java?charactorEncoding=UTF-8","root", "root"); 
        Statement s = c.createStatement();
        return s;
    }
    
}